package persistentie;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.JOptionPane;

public abstract class Mapper 
{
/*Attributen*/
	protected Connection verbinding;
	protected Statement statement;
	protected PreparedStatement pStatement;
	protected ResultSet resultaat;
	
/*Methodes*/
	protected void closeStatement() throws SQLException
	{
		resultaat.close();
		statement.close();
		resultaat=null;
		statement=null;
	}
	protected void closePreparedStatement() throws SQLException
	{
		pStatement.close();
		pStatement=null;
	}
	protected void closeConnection()
	{
		PersistentieController.getInstance().sluitVerbinding();
		verbinding=null;
	}
	protected int haalLaatstIngevoegdId(String query)
	{
		int id=0;
		try
		{
			statement = verbinding.createStatement();
			resultaat = statement.executeQuery(query);
			
			while(resultaat.next())
			{
				id = resultaat.getInt(1);
				break;
			}
			closeStatement();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return id;
	}
	protected void initQuery(String query)
	{
		try 
		{
			pStatement = verbinding.prepareStatement(query);
		}
		// detect problems interacting with the database
		catch (SQLException sqlException) 
		{
			JOptionPane.showMessageDialog(null, sqlException.getMessage(),
					"Database Error", JOptionPane.ERROR_MESSAGE);
			System.exit(1);
		}
	}	
}
